package net.jueb.frameworkDemo.orm.mongodb.springDataMongodb.codeStyle;

import java.io.IOException;
import java.util.Properties;
import org.springframework.data.mongodb.MongoDbFactory;

import net.jueb.frameworkDemo.orm.mongodb.util.MongoUtil;
import net.jueb.frameworkDemo.orm.mongodb.util.SpringMongoUtil;

public class DbUtil{

	public static String host;
	public static int port;
	public static String authDatabase;
	public static String database;
	public static String username;
	public static String password;
	private static MongoDbFactory factory;
	
	static{
		Properties ps=new Properties();
		try {
			ps.load(DbUtil.class.getResourceAsStream("mongodb.properties"));
			host=ps.getProperty("db.host");
			port=Integer.parseInt(ps.getProperty("db.port"));
			authDatabase=ps.getProperty("db.authDatabase");
			database=ps.getProperty("db.database");
			username=ps.getProperty("db.username");
			password=ps.getProperty("db.password");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static MongoDbFactory getDbFactory()
	{
		if(factory==null)
		{
			if(username==null || username.isEmpty())
			{
				factory=SpringMongoUtil.getDbFactory(MongoUtil.buildClient(host, port), database);
			}else
			{
				factory=SpringMongoUtil.getDbFactory(MongoUtil.buildClient(host, port, authDatabase, username, password), database);
			}
		}
		return factory;
	}
}
